package cn.xt.controller.user;

import cn.xt.bean.Users;
import cn.xt.service.com.ComService;
import cn.xt.service.orders.OrdersService;
import cn.xt.service.user.UserService;
import cn.xt.util.FileImageUtils;
import cn.xt.util.GetMassageCode;
import cn.xt.util.JsonUtils;
import cn.xt.util.SecurityUtils;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("/user")
public class ControlUser {
    @Autowired
    private UserService userSerive;
    @Autowired
    private ComService comService;
    @Autowired
    private OrdersService ordersService;



    /*修改手机号码*/
    @RequestMapping(value = "/UpdatePhone.json",method = RequestMethod.GET)
    @ResponseBody
    public Object UpdatePhones(@RequestParam("users_id") int users_id,@RequestParam("phone")String phone,HttpSession session){
    HashMap<String,String>map=new HashMap<String,String>();

        System.out.println("sssss修改手机号");
        //使用bool拿到UpdPhone(phone,users_id)
         boolean bool= userSerive.UpdPhone(phone,users_id);
         //使用session获取user
        Users users=(Users)session.getAttribute("user");
        //放入电话
        users.setPhone(phone);
        //放入users_id
        users.setUsers_id(users_id);
   if(bool){
       //使用sesssion传入一个user
       session.setAttribute("user",users);
       map.put("ok","true");
   }
   return JSONArray.toJSONString(map);
    }

    /*在修改手机号时判断手机号码是否存在SelemodifyPhones*/
    @RequestMapping(value = "/modifyPhones.json",method = RequestMethod.GET)
    @ResponseBody
    public Object SelemodifyPhones(@RequestParam("phones") String phones){
        System.out.println("电话号码=="+phones);
        HashMap<String,String>map=new HashMap<String,String>();
        //传入一个电话判断是否存在数据库
        Users user = userSerive.yzphone(phones);
        System.out.println("=====");
        if(user!=null){
            System.out.println("okhaha");
            //存在返回ok
            map.put("ok","true");
        }else {
            //不存在则获取验证码
            map.put("getCodes",GetMassageCode.getCode(phones));
            map.put("no","false");
        }
        return JSONArray.toJSONString(map);
    }

    /*修改用户*/
    @RequestMapping("/updateUsers.html")
    public String updateUsers(Users users,
            HttpSession session){
        System.out.println("进入修改");
        //使用bool接收users
       boolean bool= userSerive.UpdateUser(users);
       if(bool){
           //再次传入一个userSerive.user(users.getUsers_id()
           session.setAttribute("user",userSerive.user(users.getUsers_id()));
           //使用session格式转换成json格式JsonUtils.objectToJson(userSerive.user(users.getUsers_id()))
           session.setAttribute("userJson", JsonUtils.objectToJson(userSerive.user(users.getUsers_id())));
           //使用重定向还需一个liindex
           return "redirect:/user/p-center.html?liindex=3";
       }
        return "personaldata";
    }

    /*修改头像传入一个MultipartFile attach，session，HttpServletRequest以及用户users_id*/
    @RequestMapping(value = "/updateImg",method = RequestMethod.POST)
    public String UpdImage(@RequestParam(value = "imger",required = false)MultipartFile attach, HttpSession session, HttpServletRequest
                            request,@RequestParam(value = "users_id",required = false) int users_id){
        System.out.println("修改头像"+attach+",编号=="+users_id);
        /*文件上传使用帮助类FileImageUtils.ImageFile(request,attach)*/
        String IdPath=FileImageUtils.ImageFile(request,attach);
        //使用session.getAttribute()读取user
        Users user=(Users) session.getAttribute("user");
        //添加进一个idPicPath
        /*设置保存路径*/
        user.setImage(IdPath);
       //增加传入一个参数idPicPath以及users_id
        if(userSerive.updaImage(IdPath,users_id)){
            session.setAttribute("user",user);
            return "redirect:../jsp/personaldata.jsp";
        }
           //再次傳入session使用users
            //使用重定向跳转personaldata.jsp
        return null;
    }

    /*进p-center.html*/
    @RequestMapping("/p-center.html")
    /*傳入liindex這代表foot位置的下標在傳入一個model，session*/
    public String pcenterList(@RequestParam("liindex")String liindex,Model model,HttpSession session){
        //model存入一個liindex
        model.addAttribute("liindex",liindex);

        //接收用戶表
        Users user=(Users) session.getAttribute("user");
        //消息提示条数
        int redcom=comService.redcom(user.getUsers_id());
        //model存入一個com
        model.addAttribute("com",redcom);

        //查询订单总条数
        int count = ordersService.ordersCount(user.getUsers_id());
       //model存入一個count
        model.addAttribute("count",count);
        //查询未支付状态条数
        int countW = ordersService.ordersWCount(user.getUsers_id());
        //model存入一個countW
        model.addAttribute("countW",countW);
        //查询已完成的订单条数
        int countY = ordersService.ordersYCount(user.getUsers_id());
        //model存入一個countY
        model.addAttribute("countY",countY);
        return "p-center";
    }
    /*忘记密码*/
    @RequestMapping(value = "/ChangePassword.json")
    @ResponseBody
    public Object ChangePassword(@RequestParam("pwd") String pwd,@RequestParam("phone") String phone){
      //使用hashmap
        HashMap<String,String>map=new HashMap<String,String>();
        System.out.println("电话=="+phone+"密码="+pwd);
        //判斷密碼跟用戶是否存在  使用md5加密SecurityUtils.md5Hex(pwd),phone
      if(userSerive.UpdatePassword(SecurityUtils.md5Hex(pwd),phone)>0){
        map.put("ok","true");
      }
      else{
          map.put("no","false");
      }
        return JSONArray.toJSONString(map);
    }
    /*拿到short里面的值傳入一個手機號碼以及使用model*/
    @RequestMapping("/loses")
    public String lose(@RequestParam("phones") String phones, Model model){
        //model傳入電話號碼
        model.addAttribute("phone",phones);
        //直接返回lose
        return "lose";
    }
    /*判断手机号码是否存在*/
    @RequestMapping(value = "/phone.json",method = RequestMethod.GET)
    @ResponseBody
    public Object phone(@RequestParam String phone,HttpSession session){
       //使用hashmap接受
        HashMap<String,String> map=new HashMap<String,String>();
        System.out.println(phone+"======");
        Users yzphone = userSerive.yzphone(phone);
        //判断手机号是否存在如果不存在直接给用户发送验证码
        if (yzphone!=null){
            //再次傳入session
            session.setAttribute("user",yzphone);

            map.put("ok","true");
            //獲取手機號碼GetMassageCode.getCode(phone)
            map.put("getCodes",GetMassageCode.getCode(phone));
        }
        else {
            map.put("ok","false");
        }
        return JSONArray.toJSONString(map);
    }


    //修改忘记密码查询用户名是否存在
    @RequestMapping("/modifyByName.json")
    @ResponseBody
    public Object modifyByName(@RequestParam String usersname,HttpSession session){

        HashMap<String,String>map=new HashMap<String,String>();
        System.out.println("modifyByName=========="+usersname);
       Users user= userSerive.modifyByName(usersname);
       if (user!=null){
           System.out.println("成功");
           System.out.println(user.toString()+"----------");
           //再次向jsp傳入session
           session.setAttribute("user",user);


           map.put("namedefult","true");
       }else{
           map.put("namedefult","false");
       }
       return JSONArray.toJSONString(map);
    }

    //ajax验证手机号码是否存在
    @RequestMapping(value="/yzPhone.json")
    @ResponseBody
    public Object yzPhone(@RequestParam("phones") String phones){
        HashMap<String,Object> maps = new HashMap<String,Object>();
       //判断手机号码是否存在
        if(userSerive.yzphone(phones)!=null){
            maps.put("defult","true");
        }else{
            maps.put("defult","false");
        }
        return maps;
    }

    //ajax接收验证码传入路径getCode.json 以及参数为手机号码
    @RequestMapping(value="/getCode.json",method = RequestMethod.POST)
    @ResponseBody
    public Object getcode(@RequestParam("phone") String phone){
        System.out.println(phone);
        HashMap<String,Object> maps = new HashMap<String,Object>();
        //获取手机验证码
        maps.put("getCode",GetMassageCode.getCode(phone));
        return maps;
    }

    //注册
    @RequestMapping("/register.json")
    @ResponseBody
    public Object register(Users users){
        //MD5密码加密给一个固定的头像ss.jpeg
        users.setImage("ss.jpeg");
        //MD5密码SecurityUtils.md5Hex(users.getPwd())
        users.setPwd(SecurityUtils.md5Hex(users.getPwd()));
       //给一个固定用户名
        users.setUsersName("小白");
        //给一个固定的出身日期
        users.setBirthday(new Date(0000-00-00));
        HashMap<String,Object> maps = new HashMap<String,Object>();
        //判断注册用户是否大于0
        if(userSerive.register(users)>0){
            maps.put("map","true");
        }else{
            maps.put("map","false");
        }
        return maps;
    }

    //登录使用ajax传入手机号以及密码
    @RequestMapping("/userLogin.json")
    @ResponseBody
    public Object userLogin(@RequestParam("phone") String phone,@RequestParam("pwd") String pwd,HttpSession session){
        //获取手机号码以及加密密码userSerive.login
        Users user = userSerive.login(phone,SecurityUtils.md5Hex(pwd));
        //使用hashmap
        HashMap<String,Object> maps = new HashMap<String,Object>();
        //进行判断用户是否为空
        if(user!=null){
            //使用session向jsp传入user值
            session.setAttribute("user",user);
            System.out.println("user = " + user);
            //把session转成ajax，JsonUtils.objectToJson(user) 取名爲userJson
            session.setAttribute("userJson", JsonUtils.objectToJson(user));
            maps.put("defult","true");
        }else{
            maps.put("defult","false");
        }
        return maps;
    }
    /*用户注销*/
    @RequestMapping("/cancellation")
    public String Thecancellation(HttpSession session){
        System.out.println("注销");
        //讀取session中的user
        Users users= (Users) session.getAttribute("user");
        if(users!=null){
            System.out.println("----");
            //使用invalidate()注銷
            session.invalidate();
            return "redirect:/jsp/sign.jsp";
        }
            return "set";
    }
}
